package com.snsoft.katalk;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Parser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.*;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;
import net.daum.adam.publisher.AdView.AnimationType;

public class KaTalkDetail extends Activity implements OnGestureListener{
	
	protected GestureDetector gestureScanner;
	public LinearLayout ll;
	public TextView tv;
	protected ViewFlipper vf;
	public Dialog dg_img;
	public ProgressDialog mProgressDialog;
	
	private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
    private static final int MENU_ID_SAVE = Menu.FIRST + 1;
    private static final int MENU_ID_SHARE = Menu.FIRST + 2;
    private static final int MENU_ID_BACK = Menu.FIRST + 3;
    
    private static final int SELECT_IMAGE = 100;
	private static final int DIALOG_BACK_ALERT = 2;
	private static final int DIALOG_QUIT_ALERT = 1;
	private static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    
    private int cnt = 0;
    private int total = 0;
    
    private DefaultHttpClient client;
    
    private ArrayList aljson;
    private String[] items;
    private CharSequence[] page_items;
    ImageView iv1;
    ImageView iv2;
    
    private com.google.ads.AdView admobView = null;
   	private net.daum.adam.publisher.AdView adamView = null;
   	private static final String LOGTAG = "Adam";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
        
        ll  = (LinearLayout)this.findViewById(R.id.ll_top);
        tv = (TextView)this.findViewById(R.id.tv_title);
        
        
        // Loading dialog set
        dg_img = new Dialog(this, R.style.SNDialog);
        dg_img.addContentView(new ProgressBar(this), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                
        // 파라미터 받기
        Bundle extras = getIntent().getExtras();
        final String json_url = extras.getString("JSON_URL");
        //final String name = extras.getString("NAME");
        total = extras.getInt("TOTAL");

        // 카테고리명 설정
        tv.setText("1/" + total);
        
    	// JSON처리 부분
    	HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
         
        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
         
        client = new DefaultHttpClient(conMgr, params);
        
        aljson = new ArrayList<String[]>();
        
        try 
        {
        	/*
        	for(int i=1; i<=total; i+=100)
        	{
        		getJsonData(getHttpGet(json_url + "&start-index=" + i));
        	}
        	*/
        	getJsonData(getHttpGet(json_url + "&start-index=1"));
        	
			//aljson = getJsonData(getHttpGet(json_url));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                
        // View Flipper 처리 부분
        gestureScanner = new GestureDetector(this);
        vf = (ViewFlipper) findViewById(R.id.ViewFlipper01);
        
        /*
        iv = new ImageView(this);
        iv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        iv.setScaleType(ScaleType.FIT_CENTER);
        */
        iv1 = (ImageView) findViewById(R.id.imageView1);
        iv2 = (ImageView) findViewById(R.id.imageView2);
    	
        //vf.addView(iv);
    	
    	items = (String[])aljson.get(0);
    	
    	new DownloadImageAsync(iv1, iv2, vf).execute(items[1]);
    	
    	if(!items[0].equals(""))
    	{
    		Toast.makeText(this.getApplicationContext(), items[0], Toast.LENGTH_LONG).show();
    		/*
    		Toast t = Toast.makeText(this.getApplicationContext(), items[0], Toast.LENGTH_LONG);
    		t.setGravity(Gravity.TOP, 0, 0);
    		t.show();
    		*/
    	}
    	
    	
    	// 버튼 이벤트 처리
    	final ImageButton imgbtn_save = (ImageButton)findViewById(R.id.imgbtn_save);
    	final ImageButton imgbtn_share = (ImageButton)findViewById(R.id.imgbtn_share);
    	final ImageButton imgbtn_page = (ImageButton)findViewById(R.id.imgbtn_page);
    	
    	imgbtn_save.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onTopMenuClick(MENU_ID_SAVE);
			}
		});
    	
    	imgbtn_share.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onTopMenuClick(MENU_ID_SHARE);
			}
		});
    	
    	imgbtn_page.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onTopMenuClick(MENU_ID_BACK);
			}
		});
    	
        // adam 실행
        initAdam();
        
        // Admob Setting
        admobView = (com.google.ads.AdView)this.findViewById(R.id.admobView);
        AdRequest adRequest = new AdRequest();
        admobView.loadAd(adRequest);
        
        admobView.setAdListener(new AdListener() 
        {
        	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) 
        	{
			}

			public void onDismissScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onLeaveApplication(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onPresentScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onReceiveAd(Ad arg0) {
				// TODO Auto-generated method stub
			}

        });    	

    }

    private void initAdam() 
    {
		// Ad@m sdk 초기화 시작
    	adamView = (AdView) findViewById(R.id.adamView);

		// 광고 클릭시 실행할 리스너
    	adamView.setOnAdClickedListener(new OnAdClickedListener() {
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});

		// 광고 내려받기 실패했을 경우에 실행할 리스너
    	adamView.setOnAdFailedListener(new OnAdFailedListener() {
			public void OnAdFailed(AdError arg0, String arg1) {
				//Log.w(LOGTAG, arg1);
				
				admobView.setVisibility(View.VISIBLE);			// 애드몹 표시
				admobView.bringToFront();						// 애드몹 상위
			}
		});

		// 광고를 정상적으로 내려받았을 경우에 실행할 리스너
    	adamView.setOnAdLoadedListener(new OnAdLoadedListener() {
			public void OnAdLoaded() {
				Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
				
				admobView.setVisibility(View.GONE);				// 애드몹 숨김
				adamView.bringToFront();						// 아담 상위
				
				
			}
		});

		// 광고를 불러올때 실행할 리스너
    	adamView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			public void OnAdWillLoad(String arg1) {
				Log.i(LOGTAG, "광고를 불러옵니다. : " + arg1);
			}
		});

		// 광고를 닫았을때 실행할 리스너
    	adamView.setOnAdClosedListener(new OnAdClosedListener() {
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});

		// 할당 받은 clientId 설정
    	adamView.setClientId("2eecZ4xT138084bb5fd");	// Play
    	
    	adamView.setRequestInterval(12);

		// Animation 효과 : 기본 값은 AnimationType.NONE
    	adamView.setAnimationType(AnimationType.FLIP_HORIZONTAL);

    	adamView.setVisibility(View.VISIBLE);
	}
    
    @Override
	public boolean onTouchEvent(MotionEvent me)
    {    	
		return gestureScanner.onTouchEvent(me);
	}
    
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub	
		return true;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
		try 
		{
            if(e1.getX() > e2.getX() && Math.abs(e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
            {
            	
                if(cnt < aljson.size()-1)
                {	
                    cnt++;
                    
                    items = (String[])aljson.get(cnt);
            		
            		//if(items[2].equals("0"))
            		//{
	                	//ImageView iv = new ImageView(this);
	                    //iv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	                    //iv.setScaleType(ScaleType.FIT_CENTER);
	                    
	                	//vf.addView(iv);
	                	
	                	//items[2] = "1";
	                	
	                	//aljson.set(cnt, items);
	                			
                    if(cnt % 2 == 0)
                	{
                		new DownloadImageAsync(iv1, iv2, vf).execute(items[1]);
                	}
                	else
                	{
                		new DownloadImageAsync(iv2, iv1, vf).execute(items[1]);
                	}
                    	
            		//}
                	
            		if(!items[0].equals(""))
                	{
            			Toast.makeText(this.getApplicationContext(), items[0], Toast.LENGTH_LONG).show();
                	}
            		
            		// set page location
            		tv.setText((cnt + 1) + "/" + total);
            		
            		vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
    		        vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
                    vf.showNext();
                    
                }

            }
            else if (e1.getX() < e2.getX() && e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
            {
            	if(cnt > 0)
            	{
            		cnt--;
            		
            		items = (String[])aljson.get(cnt);
            		
            		//aljson.set(cnt, items);
        			
            		if(cnt % 2 == 0)
                	{
                		new DownloadImageAsync(iv1, iv2, vf).execute(items[1]);
                	}
                	else
                	{
                		new DownloadImageAsync(iv2, iv1, vf).execute(items[1]);
                	}
            		
            		if(!items[0].equals(""))
                	{
            			Toast.makeText(this.getApplicationContext(), items[0], Toast.LENGTH_LONG).show();
                	}
            		
            		// set page location
            		tv.setText((cnt + 1) + "/" + total);
            		
            		vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
    		        vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
                    vf.showPrevious();
            	}
            }
            	
        } catch (Exception e) 
        {
            // nothing
        }
		
        return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		//openOptionsMenu();
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		//openOptionsMenu();
		
		if(ll.getVisibility() == View.INVISIBLE)
		{
			ll.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_top_in));
			ll.setVisibility(View.VISIBLE);
		}
		else
		{
			ll.setAnimation(AnimationUtils.loadAnimation(this, R.anim.push_top_out));
			ll.setVisibility(View.INVISIBLE);
		}
		
		return true;
	}

	// Image Download (Flipper)
    class DownloadImageAsync extends AsyncTask<String, Void, Bitmap> 
    {
    	ImageView imageView;
    	ImageView imageViewLoading;
    	String imageURL;
    	ViewFlipper flipper;
        
    	public DownloadImageAsync(ImageView iv, ImageView iv_load, ViewFlipper flipper)
    	{
    		this.imageView = iv;
    		this.imageViewLoading = iv_load;
    		this.flipper = flipper;
    	}
    	
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			//dg_img.show();
		}

        @Override
        protected Bitmap doInBackground(String... aurl) 
        {
        	imageURL = aurl[0];
        	
        	Bitmap bitmap = ImageDownload(imageURL);
        	
        	return bitmap;
        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
             //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(Bitmap bm) 
        {
        	imageView.setImageBitmap(bm);
        	imageViewLoading.setImageResource(R.drawable.load_bg);
        	
        	//flipper.addView(imageView);
        	//bm.recycle();
        	//bm = null;
        	//((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
        	
        	//if(dg_img.isShowing())
    		//{
        	//	dg_img.dismiss();
    		//}
        	
        }
    }
    
    public Bitmap ImageDownload(String imageURL)
    {
    	try
    	{    		
    		URL url = new URL(imageURL);
    		URLConnection conn = url.openConnection();
    		conn.connect();

    		BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    		
    		//BitmapFactory.Options options = new BitmapFactory.Options();
    		//options.inSampleSize = 1;
    		//options.inPurgeable = true;
    		Bitmap bm = BitmapFactory.decodeStream(bis);
    		
    		//Bitmap bm = BitmapFactory.decodeStream(bis, null, options);
    		
    		bis.close();

    		//return loadResizeBitmap(this.getApplicationContext(), bm, imageURL);
    		return bm;
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		return null;
    	}
    }

    // Screen rotating fix
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    // 클릭 이벤트 처리
    public void onTopMenuClick(int menu_id)
    {
    	String sd = Environment.getExternalStorageDirectory().toString();	// SD카드 경로
		String fn = items[1].substring(items[1].lastIndexOf("/") + 1);
		File path = new File(sd + "/KaTalk");
		File fnnew = new File(sd + "/KaTalk", fn);
		
		// 디렉토리 없을 시 생성
		if(!path.isDirectory()) 
			path.mkdirs();
	
    	switch(menu_id)
    	{
    		case MENU_ID_SAVE:
    			if(fnnew.isFile())
    				Toast.makeText(this.getApplicationContext(), "동일한 파일이 존재합니다.", Toast.LENGTH_SHORT).show();
    			else
    				new DownloadFileAsync(MENU_ID_SAVE).execute(items[1], fn);
    			break;
    		case MENU_ID_SHARE:
    			if(fnnew.isFile())
    				onShare(fnnew);
    			else
    				new DownloadFileAsync(MENU_ID_SHARE).execute(items[1], fn);
    			break;
    		case MENU_ID_BACK:	
    			KaTalkDetail.this.finish();
    	    	overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    			break;
    	}    	
    }
    
    // Image Download
    class DownloadFileAsync extends AsyncTask<String, String, String> 
    {
    	int actiontype;
    	File f;
        
    	public DownloadFileAsync(int item_id)
    	{
    		this.actiontype = item_id;
    	}
    	
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

        @Override
        protected String doInBackground(String... aurl) 
        {
            int count;

            try 
            {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                
                String sd = Environment.getExternalStorageDirectory().toString();
                
				File path = new File(sd + "/KaTalk");
				
				if(!path.isDirectory()) 
				{
					path.mkdirs();
				}
       	     
    			String fn = aurl[1];
    			f = new File(path, fn);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(f.getAbsolutePath());

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) 
                {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            
            return aurl[1];

        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String fn) 
        {
        	//dg_img.dismiss();
        	
        	if(actiontype == MENU_ID_SAVE)
        	{
        		Toast.makeText(getApplicationContext(), "이미지를 저장했습니다.", Toast.LENGTH_LONG).show();
        		removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        		
        		// media center 새로고침
        		//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        		sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ Environment.getExternalStorageDirectory() + "/KaTalk/" + fn)));
        	}
        	else if(actiontype == MENU_ID_SHARE)
        	{
        		removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        		onShare(f);
        	}
        }
    }
    
    // 파일공유
    public void onShare(File fn)
    {
    	Intent itShare = new Intent(Intent.ACTION_SEND);
		MimeTypeMap type = MimeTypeMap.getSingleton();
		itShare.setType(type.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(fn.toString())));
		itShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fn));
		itShare.putExtra(Intent.EXTRA_TEXT, "[Copyright]" + R.string.app_name); 
		startActivity(itShare);
    }
    
    
    // http로 받기
    private String getHttpGet(String url) throws IOException
    {
        return request(new HttpGet(url));
    }
     
    private String request(HttpUriRequest request) throws IOException 
    {
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) 
            throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode());
         
        HttpEntity entity = response.getEntity();
        String result = null;
 
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
 
        return result;
    }
    
    // JSON 처리
    private void getJsonData(String jsonc) throws JSONException
    {
    	//ArrayList<String[]> al = new ArrayList<String[]>();
    	
    	JSONObject jo = new JSONObject(jsonc);
    	
    	JSONArray ja = new JSONArray(jo.getJSONObject("data").getString("items"));
    	
    	
    	for(int i=0; i<ja.length(); i++)
    	{
    		JSONObject jo_item = ja.getJSONObject(i);
    		String arr[] = {jo_item.getString("description"), jo_item.getJSONObject("media").getJSONObject("image").getString("url"), "0"};

    		aljson.add(arr);	
    	}
    	
    	//return al;
    }
    
    // Dialog Management
    @Override
    protected Dialog onCreateDialog(int id) 
    {
    	super.onCreateDialog(id);
    	
        switch (id) 
        {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("저장 중..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                return mProgressDialog;
            case DIALOG_BACK_ALERT:
            	new AlertDialog.Builder(this)
            	.setTitle("시작페이지를 선택하세요.")
            	.setItems(page_items, new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						tv.setText(page_items[which] + "/" + total);
					}
				})
				.show();   	
            default:
                return null;
        }
    }
    
    // 백키 종료
    @Override
    public void onBackPressed() 
    {
    	KaTalkDetail.this.finish();
    	overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }
    
    @Override
	public void onDestroy() {
		super.onDestroy();
	}
    
 

}